﻿// Enhanced ChannelResultViewForm.cs - 支持查看通道所有类型的多轮测量结果
using MultiDAQ_Analysis.Model;
using MultiDAQ_Analysis.Models;
using MultiDAQ_Analysis.Util;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MultiDAQ_Analysis.View.UcCenterView;

namespace MultiDAQ_Analysis.View
{
    /// <summary>
    /// 增强版通道结果查看窗口 - 支持查看所有类型的多轮测量结果
    /// </summary>
    public partial class ChannelResultViewForm : UIForm
    {
        private int channelIndex;
        private ChannelDisplayData channelDisplayData;
        private Dictionary<string, MultiRoundMeasurementData> allMeasurementResults;

        // UI 控件
        private UIRichTextBox txtResultDisplay;
        private UIButton btnRefresh;
        private UIButton btnExportAll;
        private UIButton btnPrint;
        private UILabel lblTitleInfo;

        // 打印相关字段
        private PrintDocument printDocument;
        private string[] printLines;
        private int printLineIndex;

        // 测量类型显示名称映射
        private static readonly Dictionary<string, string> MeasurementTypeNames = new Dictionary<string, string>
        {
            {"Background", "本底测量"},
            {"WorkingSourceEfficiency", "工作源效率测量"},
            {"StandardSourceEfficiency", "标准源效率测量"},
            {"WaterSample", "水样品测量"},
            {"BioSample", "生物样品测量"},
            {"GasSample", "气体样品测量"},
            {"EnvSample", "环境样品测量"}
        };

        public ChannelResultViewForm(int channelIndex)
        {
            this.channelIndex = channelIndex;
            this.channelDisplayData = null;
            InitializeComponent();
            InitializePrintComponents();
            SetupForm();
            _ = LoadAllMeasurementDataAsync();
        }

        public ChannelResultViewForm(ChannelDisplayData displayData)
        {
            this.channelIndex = displayData.ChannelIndex;
            this.channelDisplayData = displayData;
            InitializeComponent();
            InitializePrintComponents();
            SetupForm();
            _ = LoadAllMeasurementDataAsync();
        }

        /// <summary>
        /// 初始化打印组件
        /// </summary>
        private void InitializePrintComponents()
        {
            printDocument = new PrintDocument();
            printDocument.PrintPage += PrintDocument_PrintPage;
            printDocument.DocumentName = $"通道{channelIndex + 1}测量结果报告";
        }



        private void SetupForm()
        {
            // 创建主布局
            var mainLayout = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 1,
                RowCount = 3,
                Padding = new Padding(15)
            };

            // 设置行样式
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60)); // 标题区
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); // 内容区
            mainLayout.RowStyles.Add(new RowStyle(SizeType.Absolute, 60)); // 按钮区

            // 创建标题区面板
            var titlePanel = CreateTitlePanel();
            mainLayout.Controls.Add(titlePanel, 0, 0);

            // 创建内容显示区
            txtResultDisplay = new UIRichTextBox
            {
                Dock = DockStyle.Fill,
                Font = new Font("Consolas", 9.5F),
                ReadOnly = true,
                BackColor = Color.White
            };
            mainLayout.Controls.Add(txtResultDisplay, 0, 1);

            // 创建底部按钮区
            var buttonPanel = CreateButtonPanel();
            mainLayout.Controls.Add(buttonPanel, 0, 2);

            this.Controls.Add(mainLayout);
        }

        private Panel CreateTitlePanel()
        {
            var titlePanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 60,
                BackColor = Color.FromArgb(243, 249, 255)
            };

            lblTitleInfo = new UILabel
            {
                Text = $"通道 {channelIndex + 1} 所有测量结果",
                AutoSize = true,
                Font = new Font("微软雅黑", 14F, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 158, 255),
                Location = new Point(20, 18)
            };

            btnRefresh = new UIButton
            {
                Text = "刷新数据",
                Size = new Size(90, 35),
                FillColor = Color.FromArgb(64, 158, 255),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Top | AnchorStyles.Right
            };
            btnRefresh.Click += BtnRefresh_Click;

            titlePanel.Controls.Add(lblTitleInfo);
            titlePanel.Controls.Add(btnRefresh);

            // 处理窗体大小变化时按钮位置调整
            titlePanel.SizeChanged += (s, e) =>
            {
                btnRefresh.Location = new Point(titlePanel.Width - 110, 13);
            };

            return titlePanel;
        }

        private Panel CreateButtonPanel()
        {
            var buttonPanel = new Panel
            {
                Dock = DockStyle.Fill,
                Height = 60
            };

            btnExportAll = new UIButton
            {
                Text = "导出报告",
                Size = new Size(100, 40),
                FillColor = Color.FromArgb(103, 194, 58),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnExportAll.Click += BtnExportAll_Click;

            btnPrint = new UIButton
            {
                Text = "打印报告",
                Size = new Size(100, 40),
                FillColor = Color.FromArgb(24, 144, 255),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnPrint.Click += BtnPrint_Click;

            var btnClose = new UIButton
            {
                Text = "关闭",
                Size = new Size(80, 40),
                FillColor = Color.FromArgb(255, 87, 87),
                ForeColor = Color.White,
                Cursor = Cursors.Hand,
                Anchor = AnchorStyles.Bottom | AnchorStyles.Right
            };
            btnClose.Click += (s, e) => this.Close();

            buttonPanel.Controls.Add(btnExportAll);
            buttonPanel.Controls.Add(btnPrint);
            buttonPanel.Controls.Add(btnClose);

            // 处理窗体大小变化时按钮位置调整
            buttonPanel.SizeChanged += (s, e) =>
            {
                btnExportAll.Location = new Point(buttonPanel.Width - 310, 10);
                btnPrint.Location = new Point(buttonPanel.Width - 200, 10);
                btnClose.Location = new Point(buttonPanel.Width - 90, 10);
            };

            return buttonPanel;
        }

        /// <summary>
        /// 加载该通道所有类型的测量数据
        /// </summary>
        private async Task LoadAllMeasurementDataAsync()
        {
            try
            {
                // 显示加载提示
                if (txtResultDisplay != null)
                {
                    txtResultDisplay.Text = "正在加载通道测量数据，请稍候...";
                }

                if (btnRefresh != null)
                {
                    btnRefresh.Enabled = false;
                    btnRefresh.Text = "加载中...";
                }

                allMeasurementResults = new Dictionary<string, MultiRoundMeasurementData>();

                // 加载所有测量类型的数据
                foreach (var measurementType in MeasurementTypeNames.Keys)
                {
                    try
                    {
                        var data = await ChannelBasedJsonDataManager.GetChannelMeasurementAsync(channelIndex, measurementType);
                        if (data != null)
                        {
                            allMeasurementResults[measurementType] = data;
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine($"加载 {measurementType} 数据失败: {ex.Message}");
                    }
                }

                // 构建结果显示
                BuildResultDisplay();
            }
            catch (Exception ex)
            {
                if (txtResultDisplay != null)
                {
                    txtResultDisplay.Text = $"加载测量结果失败: {ex.Message}";
                }
                UIMessageBox.ShowError($"加载测量结果失败：{ex.Message}");
            }
            finally
            {
                if (btnRefresh != null)
                {
                    btnRefresh.Enabled = true;
                    btnRefresh.Text = "刷新数据";
                }
            }
        }

        /// <summary>
        /// 构建结果显示界面
        /// </summary>
        private void BuildResultDisplay()
        {
            try
            {
                string resultText = BuildCompleteResultText();
                txtResultDisplay.Text = resultText;
            }
            catch (Exception ex)
            {
                txtResultDisplay.Text = $"构建结果显示失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 构建完整结果文本 - 统一显示所有内容
        /// </summary>
        private string BuildCompleteResultText()
        {
            var sb = new StringBuilder();

            // 标题
            sb.AppendLine($"=== 通道 {channelIndex + 1} 所有测量结果报告 ===");
            sb.AppendLine($"生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine();

            // 通道基本信息
            BuildChannelBasicInfo(sb);
            sb.AppendLine();

            if (allMeasurementResults.Count == 0)
            {
                sb.AppendLine("【测量结果】");
                sb.AppendLine("该通道暂无任何测量结果。");
                sb.AppendLine();
                sb.AppendLine("建议：");
                sb.AppendLine("1. 检查该通道是否已启用");
                sb.AppendLine("2. 确认是否已进行过相关测量");
                sb.AppendLine("3. 检查数据存储路径是否正确");
                return sb.ToString();
            }

            // 测量完成情况汇总
            BuildMeasurementSummary(sb);
            sb.AppendLine();

            // 各测量类型详细结果
            foreach (var kvp in allMeasurementResults.OrderBy(x => GetMeasurementTypeOrder(x.Key)))
            {
                BuildMeasurementTypeDetail(sb, kvp.Key, kvp.Value);
                sb.AppendLine();
            }

            // 统计分析
            BuildStatisticalAnalysis(sb);

            return sb.ToString();
        }

        private void BuildChannelBasicInfo(StringBuilder sb)
        {
            sb.AppendLine("【通道基本信息】");

            try
            {
                var channelData = ChannelDataManager.LoadChannelData(channelIndex);
                sb.AppendLine($"通道编号: 通道 {channelIndex + 1}");
                sb.AppendLine($"状态: {(channelData.Thresholds.IsSelected ? "已启用" : "未启用")}");
                sb.AppendLine($"最后更新: {channelData.LastModified:yyyy-MM-dd HH:mm:ss}");
                sb.AppendLine($"Alpha阈值: {channelData.Thresholds.AlphaLow:F6} - {channelData.Thresholds.AlphaHigh:F6}");
                sb.AppendLine($"Beta阈值: {channelData.Thresholds.BetaLow:F6} - {channelData.Thresholds.BetaHigh:F6}");
                sb.AppendLine($"已完成测量类型: {allMeasurementResults.Count} / {MeasurementTypeNames.Count}");
                sb.AppendLine($"总测量轮数: {allMeasurementResults.Values.Sum(d => d.TotalRounds)}");
            }
            catch (Exception ex)
            {
                sb.AppendLine($"通道配置信息获取失败: {ex.Message}");
            }
        }

        private void BuildMeasurementSummary(StringBuilder sb)
        {
            sb.AppendLine("【测量完成情况汇总】");
            sb.AppendLine($"{"测量类型",-20} {"完成状态",-8} {"总轮数",-8} {"开始时间",-16} {"耗时(分)",-8} {"平均结果(α)",-12}");
            sb.AppendLine(new string('-', 85));

            foreach (var typeKvp in MeasurementTypeNames.OrderBy(x => GetMeasurementTypeOrder(x.Key)))
            {
                string measurementType = typeKvp.Key;
                string displayName = typeKvp.Value;

                if (allMeasurementResults.ContainsKey(measurementType))
                {
                    var data = allMeasurementResults[measurementType];
                    string avgAlpha = "---";

                    if (data.ChannelResults.ContainsKey(channelIndex) &&
                        data.ChannelResults[channelIndex].AverageResult != null)
                    {
                        avgAlpha = data.ChannelResults[channelIndex].AverageResult.AlphaResult.ToString("F3");
                    }

                    double duration = (data.EndTime - data.StartTime).TotalMinutes;
                    sb.AppendLine($"{displayName,-20} {"已完成",-8} {data.TotalRounds,-8} " +
                                 $"{data.StartTime:MM-dd HH:mm,-16} {duration,-8:F1} {avgAlpha,-12}");
                }
                else
                {
                    sb.AppendLine($"{displayName,-20} {"未完成",-8} {"---",-8} {"---",-16} {"---",-8} {"---",-12}");
                }
            }
        }

        private void BuildMeasurementTypeDetail(StringBuilder sb, string measurementType, MultiRoundMeasurementData data)
        {
            string displayName = GetMeasurementTypeDisplayName(measurementType);
            sb.AppendLine($"【{displayName}】");

            // 基本信息
            sb.AppendLine($"测量时间: {data.StartTime:yyyy-MM-dd HH:mm:ss} - {data.EndTime:yyyy-MM-dd HH:mm:ss}");
            sb.AppendLine($"总轮数: {data.TotalRounds}  每轮时间: {data.MeasurementTimeMinutes}分钟  " +
                         $"总耗时: {(data.EndTime - data.StartTime).TotalMinutes:F1}分钟");
            //sb.AppendLine($"测量ID: {data.MeasurementId}");

            // 参数配置
            var parameterInfo = BuildParameterInfoText(measurementType, data.Parameters);
            if (!string.IsNullOrEmpty(parameterInfo))
            {
                sb.AppendLine($"参数配置: {parameterInfo}");
            }

            // 该通道的结果
            if (data.ChannelResults.ContainsKey(channelIndex))
            {
                var channelResult = data.ChannelResults[channelIndex];

                // 平均结果
                if (channelResult.AverageResult != null)
                {
                    var avgResult = channelResult.AverageResult;
                    sb.AppendLine($"平均结果: α = {avgResult.AlphaResult:F6}  β = {avgResult.BetaResult:F6}");
                    sb.AppendLine($"平均计数率: α = {avgResult.AlphaCountRate:F3}/s  β = {avgResult.BetaCountRate:F3}/s");
                }

                // 统计信息
                if (channelResult.Statistics != null)
                {
                    var stats = channelResult.Statistics;
                    sb.AppendLine($"统计分析: α标准差 = {stats.AlphaStandardDeviation:F6}  β标准差 = {stats.BetaStandardDeviation:F6}");
                    sb.AppendLine($"相对误差: α = {stats.AlphaRelativeError:F2}%  β = {stats.BetaRelativeError:F2}%");
                }

                // 各轮详细结果
                sb.AppendLine();
                sb.AppendLine($"{"轮次",-4} {"α结果",-12} {"β结果",-12} {"α计数率(/s)",-12} {"β计数率(/s)",-12} {"测量时间",-10}");
                sb.AppendLine(new string('-', 70));

                foreach (var roundResult in channelResult.RoundResults.OrderBy(r => r.RoundNumber))
                {
                    sb.AppendLine($"{roundResult.RoundNumber,-4} {roundResult.AlphaResult,-12:F6} " +
                                 $"{roundResult.BetaResult,-12:F6} {roundResult.AlphaCountRate,-12:F3} " +
                                 $"{roundResult.BetaCountRate,-12:F3} {roundResult.Timestamp:HH:mm:ss,-10}");
                }

                // 如果有总点数信息，额外显示
                var roundsWithCounts = channelResult.RoundResults.Where(r => r.AlphaTotalCounts > 0 || r.BetaTotalCounts > 0);
                if (roundsWithCounts.Any())
                {
                    sb.AppendLine();
                    sb.AppendLine("各轮总点数信息:");
                    sb.AppendLine($"{"轮次",-4} {"α总点数",-10} {"β总点数",-10} {"测量时长(秒)",-12}");
                    sb.AppendLine(new string('-', 40));

                    foreach (var roundResult in roundsWithCounts.OrderBy(r => r.RoundNumber))
                    {
                        sb.AppendLine($"{roundResult.RoundNumber,-4} {roundResult.AlphaTotalCounts,-10} " +
                                     $"{roundResult.BetaTotalCounts,-10} {roundResult.MeasurementDurationSeconds,-12}");
                    }
                }
            }
            else
            {
                sb.AppendLine("注意: 该通道在此次测量中无数据记录");
            }
        }

        private void BuildStatisticalAnalysis(StringBuilder sb)
        {
            sb.AppendLine("【统计分析】");

            // 整体统计
            int totalMeasurements = allMeasurementResults.Count;
            int totalRounds = allMeasurementResults.Values.Sum(data => data.TotalRounds);
            var totalDuration = allMeasurementResults.Values.Sum(data => (data.EndTime - data.StartTime).TotalMinutes);

            sb.AppendLine($"├─ 完成测量类型: {totalMeasurements} / {MeasurementTypeNames.Count}");
            sb.AppendLine($"├─ 总测量轮数: {totalRounds}");
            sb.AppendLine($"├─ 总测量时长: {totalDuration:F1} 分钟 ({totalDuration / 60:F1} 小时)");

            if (totalMeasurements > 0)
            {
                double avgRoundsPerMeasurement = (double)totalRounds / totalMeasurements;
                double avgDurationPerMeasurement = totalDuration / totalMeasurements;
                sb.AppendLine($"├─ 平均每种测量轮数: {avgRoundsPerMeasurement:F1}");
                sb.AppendLine($"├─ 平均每种测量耗时: {avgDurationPerMeasurement:F1} 分钟");

                // 最早和最晚测量时间
                var earliestTime = allMeasurementResults.Values.Min(data => data.StartTime);
                var latestTime = allMeasurementResults.Values.Max(data => data.EndTime);
                sb.AppendLine($"├─ 最早测量时间: {earliestTime:yyyy-MM-dd HH:mm:ss}");
                sb.AppendLine($"└─ 最晚测量时间: {latestTime:yyyy-MM-dd HH:mm:ss}");
            }

            sb.AppendLine();
            sb.AppendLine("【数据完整性检查】");

            bool allDataComplete = true;
            foreach (var kvp in allMeasurementResults)
            {
                if (!kvp.Value.ChannelResults.ContainsKey(channelIndex))
                {
                    sb.AppendLine($"⚠ {GetMeasurementTypeDisplayName(kvp.Key)}: 缺少该通道数据");
                    allDataComplete = false;
                }
                else if (kvp.Value.ChannelResults[channelIndex].AverageResult == null)
                {
                    sb.AppendLine($"⚠ {GetMeasurementTypeDisplayName(kvp.Key)}: 缺少平均结果");
                    allDataComplete = false;
                }
            }

            if (allDataComplete)
            {
                sb.AppendLine("✓ 所有测量数据完整");
            }

            sb.AppendLine();
            sb.AppendLine($"报告生成时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        }

        /// <summary>
        /// 构建参数信息文本 - 增强版本
        /// </summary>
        private string BuildParameterInfoText(string measurementType, object parameters)
        {
            if (parameters == null) return "";

            try
            {
                var parametersJson = JsonConvert.SerializeObject(parameters, Formatting.None);
                var paramObj = JsonConvert.DeserializeObject<dynamic>(parametersJson);

                switch (measurementType)
                {
                    case "WorkingSourceEfficiency":
                        return $"几何因子={paramObj.GeometryFactor ?? "未设置"}";

                    case "StandardSourceEfficiency":
                        return "标准源参数已配置";

                    case "WaterSample":
                        return $"水样体积={paramObj.WaterVolume ?? "未设置"}L, 残渣量={paramObj.TotalResidueAmount ?? "未设置"}g, " +
                               $"测试质量={paramObj.TestedSampleMass ?? "未设置"}g";

                    case "BioSample":
                        return $"鲜样重={paramObj.FreshSampleWeight ?? "未设置"}g, 总灰重={paramObj.TotalAshWeight ?? "未设置"}g, " +
                               $"回收率={paramObj.RecoveryRate ?? "未设置"}%";

                    case "GasSample":
                        return $"采样体积={paramObj.SamplingVolume ?? "未设置"}m³, 过滤效率={paramObj.FilterEfficiency ?? "未设置"}%, " +
                               $"吸收因子={paramObj.AbsorptionFactor ?? "未设置"}";

                    case "EnvSample":
                        return $"测试质量={paramObj.TestedSampleMass ?? "未设置"}g, 修正因子={paramObj.CorrectionFactor ?? "未设置"}";

                    case "Background":
                        return "本底测量参数";

                    default:
                        return "参数已配置";
                }
            }
            catch (Exception ex)
            {
                return $"参数解析失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 获取测量类型显示名称
        /// </summary>
        private string GetMeasurementTypeDisplayName(string englishType)
        {
            return MeasurementTypeNames.ContainsKey(englishType)
                ? MeasurementTypeNames[englishType]
                : englishType;
        }

        /// <summary>
        /// 获取测量类型排序顺序
        /// </summary>
        private int GetMeasurementTypeOrder(string measurementType)
        {
            var order = new Dictionary<string, int>
            {
                {"Background", 1},
                {"StandardSourceEfficiency", 2},
                {"WorkingSourceEfficiency", 3},
                {"WaterSample", 4},
                {"BioSample", 5},
                {"GasSample", 6},
                {"EnvSample", 7}
            };
            return order.ContainsKey(measurementType) ? order[measurementType] : 99;
        }

        #region 事件处理方法

        /// <summary>
        /// 刷新数据
        /// </summary>
        private async void BtnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                await LoadAllMeasurementDataAsync();
                UIMessageBox.ShowSuccess("数据已刷新！");
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"刷新数据失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 导出所有数据
        /// </summary>
        private void BtnExportAll_Click(object sender, EventArgs e)
        {
            try
            {
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*",
                    DefaultExt = "txt",
                    FileName = $"通道{channelIndex + 1}_所有测量结果_{DateTime.Now:yyyyMMdd_HHmmss}.txt"
                };

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    System.IO.File.WriteAllText(saveFileDialog.FileName, txtResultDisplay.Text, System.Text.Encoding.UTF8);
                    UIMessageBox.ShowSuccess($"报告已导出到：\n{saveFileDialog.FileName}");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"导出失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 打印按钮事件
        /// </summary>
        private void BtnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtResultDisplay.Text))
                {
                    UIMessageBox.ShowWarning("没有可打印的内容！");
                    return;
                }

                printLines = txtResultDisplay.Text.Split('\n');
                printLineIndex = 0;

                PrintDialog printDialog = new PrintDialog();
                printDialog.Document = printDocument;

                if (printDialog.ShowDialog() == DialogResult.OK)
                {
                    printDocument.Print();
                    UIMessageBox.ShowSuccess("打印任务已发送到打印机！");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"打印失败：{ex.Message}");
            }
        }

        #endregion

        #region 打印相关方法

        /// <summary>
        /// 打印文档的PrintPage事件处理
        /// </summary>
        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                Font printFont = new Font("宋体", 9F);
                Font titleFont = new Font("宋体", 12F, FontStyle.Bold);
                float leftMargin = e.MarginBounds.Left;
                float topMargin = e.MarginBounds.Top;
                float yPos = topMargin;
                float lineHeight = printFont.GetHeight(e.Graphics);

                // 打印标题
                string title = $"通道{channelIndex + 1}测量结果报告 - 第{((printLineIndex == 0) ? 1 : (printLineIndex / 50 + 1))}页";
                e.Graphics.DrawString(title, titleFont, Brushes.Black, leftMargin, yPos);
                yPos += titleFont.GetHeight(e.Graphics) * 2;

                // 计算每页可打印的行数
                int linesPerPage = (int)((e.MarginBounds.Height - titleFont.GetHeight(e.Graphics) * 2) / lineHeight);
                int linesOnThisPage = 0;

                // 打印文本内容
                while (printLineIndex < printLines.Length && linesOnThisPage < linesPerPage)
                {
                    string line = printLines[printLineIndex];

                    // 检查是否需要换行（行太长）
                    SizeF textSize = e.Graphics.MeasureString(line, printFont);
                    if (textSize.Width > e.MarginBounds.Width)
                    {
                        // 分割长行
                        int charsPerLine = (int)(line.Length * e.MarginBounds.Width / textSize.Width) - 5;
                        if (charsPerLine > 0)
                        {
                            string subLine = line.Substring(0, Math.Min(charsPerLine, line.Length));
                            e.Graphics.DrawString(subLine, printFont, Brushes.Black, leftMargin, yPos);

                            if (line.Length > charsPerLine)
                            {
                                printLines[printLineIndex] = line.Substring(charsPerLine);
                            }
                            else
                            {
                                printLineIndex++;
                            }
                        }
                        else
                        {
                            e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
                            printLineIndex++;
                        }
                    }
                    else
                    {
                        e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
                        printLineIndex++;
                    }

                    yPos += lineHeight;
                    linesOnThisPage++;
                }

                // 判断是否还有更多页需要打印
                e.HasMorePages = (printLineIndex < printLines.Length);
            }
            catch (Exception ex)
            {
                UIMessageBox.ShowError($"打印过程中发生错误：{ex.Message}");
                e.HasMorePages = false;
            }
        }

        /// <summary>
        /// 窗体关闭时清理资源
        /// </summary>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            printDocument?.Dispose();
            base.OnFormClosed(e);
        }

        #endregion
    }
}